<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/6/17
 * Time: 12:03
 */

namespace app\admin\service;


use app\model\AuthModel;
use app\model\RoleAuthModel;
use think\facade\Db;

class AuthService
{
    protected $model;

    public function __construct()
    {
        $this->model = new AuthModel();
    }

    /**
     * 权限添加
     * @param $data
     * @return bool
     */
    public function save($data)
    {
        return $this->model->save($data);
    }

    /**
     * 权限查询
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function findAll()
    {
        return $this->model->select();
    }

    /**
     * 权限编辑
     * @param $id
     * @param $data
     * @return AuthModel
     */
    public function update($id, $data)
    {
        return $this->model->where('id', $id)->update($data);
    }

    /**
     * 权限删除
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        // ①、删除auth里面id = $id的数据
        // ②、删除role_auth里面auth_id = $id的数据
        $db = new Db();
        $db->startTrans();
        try {
            $this->model->where('id', $id)->delete();
            $roleAuthModel = new RoleAuthModel();
            $roleAuthModel->where('auth_id', $id)->delete();
            // 提交事务
            $db->commit();
            return 1;
        } catch (\Exception $e) {
            // 回滚事务
            $db->rollback();
            return 0;
        }
    }

    /**
     * 通过auth_ids集获取path路径集
     * @param $auth_ids
     * @return array
     */
    public function getPathByAuthIds($auth_ids)
    {
        return array_filter($this->model->where('id', 'in', $auth_ids)->column('path'));
    }

    /**
     * 获取菜单列表
     * @param null $data
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMenu($data = null)
    {
        $where = ['is_show' => 10, 'm' => 'admin'];
        if (!empty($data)) {
            $where = [
                ['id', 'in', $data],
                ['is_show', '=', '10'],
                ['m', '=', 'admin']
            ];
        }
        return $this->model->where($where)->field('id,pid,name,path,icon')->order('sorted desc')->select();
    }
}